/**
 * Created by lsj on 2018/5/10.
 */
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {UserService} from './user.service';
import {Observable} from "rxjs";


@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private router: Router, private userService: UserService) { }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean {
    // return this.checkLogin();
    return this.checkLoginInLocalstore();
  }

  checkLogin(): Observable<boolean>|boolean {
    if (this.userService.authenticated) {
      console.log('AuthGuard checkLogin() authenticated: ' + this.userService.authenticated);
      return this.userService.authenticated;
    }
    const that = this;
    const observable = Observable.create(function (observer) {
      const httpObs = that.userService.getUserData();
      httpObs.subscribe(res => {
        if (res['status'] === 200) {
          observer.next(true);
        } else {
          that.router.navigate(['/login']);
          observer.next(false);
        }
        observer.complete();
      });
    });
    return observable;
  }

  checkLoginInLocalstore():boolean {
    if (this.userService.isLogin())
      return true;
    else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}
